import { observable, action } from 'mobx-miniprogram';
const cloudHelper = require('../../../helpers/cloud_helper.js');
const pageHelper = require('../../../helpers/page_helper.js');
const timeHelper = require('../../../helpers/time_helper.js');

// 定义工作台相关的API路由
const API_ROUTES = {
  WORK_DATA: 'home/work_data',
  DYNAMIC_LIST: 'home/dynamic_list',
  STATISTICS: 'home/statistics',
  NOTIFICATIONS: 'home/dynamic_list',
  MARK_READ: 'home/mark_read'
};

// 缓存键
const CACHE_KEY = 'INDEX_STORE';

// 创建工作台/首页模块Store
const createStore = function() {
  return observable({
    // 状态管理
    pageStatus: {
      loading: false,
      refreshing: false,
      error: null,
      isLoading: false,
      isError: false,
      errorMessage: '',
      
      // 各部分数据加载状态
      workDataLoading: false,
      dynamicListLoading: false,
      statisticsLoading: false,
      notificationsLoading: false
    },

    // 工作台数据
    workData: {
      waitList: [],  // 待办列表
      todoCount: 0,  // 当月待办总数
      doneCount: 0,  // 已办总数
      myCount: 0,    // 我发起的
      approvalTotal: 0, // 审批总数
      taskTotal: 0,     // 任务总数
      taskDoing: 0,     // 进行中任务
      projectTotal: 0,  // 项目总数
      month: timeHelper.fmtDateCN() // 当前月份使用timeHelper
    },
    statItems: [
      {key: 'taskTotal', label: '任务'},
      {key: 'taskDoing', label: '进行中'},
      {key: 'approvalTotal', label: '审批'},
      {key: 'projectTotal', label: '研发'}
    ],
    
    // 统计数据
    statistics: {
      docStats: {
        title: '知识文档',
        count: 0,
        percent: 0
      },
      meetingStats: {
        title: '会议预定',
        count: 0,
        percent: 0
      },
      deviceStats: {
        title: '设备借用',
        count: 0,
        percent: 0
      },
      carStats: {
        title: '车辆预约',
        count: 0,
        percent: 0
      }
    },
    
    // 统计数据
    statCards: [
      {key: 'completionRate', title: '任务完成率'},
      {key: 'passRate', title: '审批通过率'},
      {key: 'progressRate', title: '项目进度'}
    ],
    
    // 动态数据
    dynamicList: [],
    
    // 通知数据
    notifications: [],
    unreadNotificationCount: 0,
    
    // 每日格言
    dailyQuote: {
      content: '创新是引领发展的第一动力',
      author: 'ABS'
    },
    
    // 快捷链接
    quickLinks: [
      {
        title: '我的审批',
        icon: '/projects/oa/images/tabbar/flow.png',
        url: '../../flow/my_list/flow_my_list'
      },
      {
        title: '待我审批',
        icon: '/projects/oa/images/tabbar/approve.png',
        url: '../../flow/my_checking/flow_my_checking'
      },
      {
        title: '已审批',
        icon: '/projects/oa/images/tabbar/checked.png',
        url: '../../flow/my_checked/flow_my_checked'
      }
    ],
    
    // 页面加载状态设置
    setPageLoading: action(function(loading) {
      this.pageStatus.loading = loading;
    }),
    
    // 页面刷新状态设置
    setPageRefreshing: action(function(refreshing) {
      this.pageStatus.refreshing = refreshing;
    }),
    
    // 页面错误状态设置
    setPageError: action(function(error) {
      this.pageStatus.error = error;
    }),
    
    // 清除页面错误
    clearPageError: action(function() {
      this.pageStatus.error = null;
    }),
    
    // 更新工作区数据
    updateWorkData: action(function(data) {
      // 映射后端返回的数据字段到前端期望的字段名
      if (data) {
        // 创建一个新对象，保留原始数据
        const mappedData = { ...data };
        
        // 将todoCount和doneCount映射到approvalTotal
        if (data.todoCount !== undefined || data.doneCount !== undefined) {
          mappedData.approvalTotal = (data.todoCount || 0) + (data.doneCount || 0);
        }
        
        // 映射其他字段
        if (data.taskCount !== undefined) {
          mappedData.taskTotal = data.taskCount;
        }
        
        if (data.projectCount !== undefined) {
          mappedData.projectTotal = data.projectCount;
        }
        
        // 添加进行中任务计数（如果后端没有提供，默认为0）
        if (!mappedData.taskDoing) {
          mappedData.taskDoing = 0;
        }
        
        // 更新状态
        this.workData = mappedData;
      } else {
        this.workData = {};
      }
    }),
    
    // 更新统计数据
    updateStatistics: action(function(data) {
      this.statistics = data || {};
    }),
    
    // 更新动态列表
    updateDynamicList: action(function(list) {
      this.dynamicList = list || [];
    }),
    
    // 更新通知列表
    updateNotifications: action(function(list) {
      this.notifications = list || [];
      // 计算未读通知数量
      this.unreadNotificationCount = (list || []).filter(item => item.status === 'unread').length;
    }),
    
    // 更新快捷链接
    updateQuickLinks: action(function(links) {
      this.quickLinks = links || this.quickLinks;
    }),
    
    // 将通知标记为已读
    markNotificationAsRead: action(function(id) {
      const notification = this.notifications.find(item => item._id === id);
      if (notification) {
        notification.status = 'read';
        this.unreadNotificationCount = this.notifications.filter(item => item.status === 'unread').length;
      }
    }),

    // 清除缓存
    clearCache: action(function() {
      // 仅清除状态，不做任何网络请求
      this.workData = {};
      this.statistics = {};
      this.dynamicList = [];
      this.notifications = [];
      this.unreadNotificationCount = 0;
    }),
    
    // 加载工作区数据
    loadWorkData: action(async function() {
      try {
        this.setPageStatus('workDataLoading', true);
        
        console.log('[工作台] 开始获取工作台数据...');
        const result = await cloudHelper.callCloudData(API_ROUTES.WORK_DATA, {});
        console.log('[工作台] 工作台数据返回结果:', result);
        
        if (result) {
          // 更新工作数据
          this.updateWorkData(result);
          console.log('[工作台] 工作台数据已更新:', this.workData);
        } else {
          console.warn('[工作台] 工作台数据返回为空');
        }
        
        this.setPageStatus('workDataLoading', false);
        return result;
      } catch (error) {
        console.error('[工作台] 加载工作区数据失败:', error);
        this.setPageError(error.message || '加载数据失败');
        this.setPageStatus('workDataLoading', false);
        throw error;
      }
    }),
    
    // 加载统计数据
    loadStatistics: action(async function() {
      try {
        this.setPageStatus('statisticsLoading', true);
        
        const result = await cloudHelper.callCloudData(API_ROUTES.STATISTICS, {});
        
        if (result) {
          // 更新统计数据
          this.updateStatistics(result);
        }
        
        this.setPageStatus('statisticsLoading', false);
        return result;
      } catch (error) {
        console.error('加载统计数据失败:', error);
        this.setPageError(error.message || '加载数据失败');
        this.setPageStatus('statisticsLoading', false);
        throw error;
      }
    }),
    
    // 加载动态列表
    loadDynamicList: action(async function() {
      try {
        this.setPageStatus('dynamicListLoading', true);
        
        const result = await cloudHelper.callCloudData(API_ROUTES.DYNAMIC_LIST, {});
        
        if (result && result.list) {
          // 处理时间格式
          const formattedList = result.list.map(item => ({
            ...item,
            time: item.time ? timeHelper.timestamp2Time(item.time, 'M-D h:m') : '',
            timeDesc: pageHelper.fromNow(item.time)
          }));
          
          // 更新动态列表
          this.updateDynamicList(formattedList);
        }
        
        this.setPageStatus('dynamicListLoading', false);
        return result;
      } catch (error) {
        console.error('加载动态列表失败:', error);
        this.setPageError(error.message || '加载数据失败');
        this.setPageStatus('dynamicListLoading', false);
        throw error;
      }
    }),
    
    // 加载通知列表
    loadNotifications: action(async function() {
      try {
        this.setPageStatus('notificationsLoading', true);
        
        const result = await cloudHelper.callCloudData(API_ROUTES.NOTIFICATIONS, {});
        
        if (result && result.list) {
          // 处理时间格式
          const formattedList = result.list.map(item => ({
            ...item,
            time: item.time ? timeHelper.timestamp2Time(item.time, 'M-D h:m') : '',
            timeDesc: pageHelper.fromNow(item.time)
          }));
          
          // 更新通知列表
          this.updateNotifications(formattedList);
        }
        
        this.setPageStatus('notificationsLoading', false);
        return result;
      } catch (error) {
        console.error('加载通知列表失败:', error);
        this.setPageError(error.message || '加载数据失败');
        this.setPageStatus('notificationsLoading', false);
        throw error;
      }
    }),
    
    // 后台刷新
    backgroundRefresh: action(async function() {
      try {
        console.log('开始后台刷新工作台数据...');
        
        // 并行加载数据，但不设置loading状态
        const [workDataRes, dynamicListRes, statisticsRes, notificationsRes] = await Promise.all([
          this.loadWorkDataSilent(),
          this.loadDynamicListSilent(),
          this.loadStatisticsSilent(),
          this.loadNotificationsSilent()
        ]);
        
        console.log('后台刷新工作台数据完成');
        
        return {
          workData: workDataRes,
          dynamicList: dynamicListRes,
          statistics: statisticsRes,
          notifications: notificationsRes
        };
      } catch (error) {
        console.error('后台刷新数据失败:', error);
        // 静默失败，不更新错误状态
        return null;
      }
    }),
    
    // 加载所有数据
    loadAllData: action(async function() {
      try {
        // 设置整体加载状态
        this.setPageStatus('isLoading', true);
        this.setPageStatus('isError', false);
        this.setPageStatus('errorMessage', '');
        
        // 设置各部分加载状态
        this.setPageStatus('workDataLoading', true);
        this.setPageStatus('dynamicListLoading', true);
        this.setPageStatus('statisticsLoading', true);
        this.setPageStatus('notificationsLoading', true);
        
        // 使用Promise.all并行加载多个数据集
        const [workDataRes, dynamicListRes, statisticsRes, notificationsRes] = await Promise.all([
          this.loadWorkData(),
          this.loadDynamicList(),
          this.loadStatistics(),
          this.loadNotifications()
        ]);
        
        // 整体加载完成
        this.setPageStatus('isLoading', false);
        
        return {
          workData: workDataRes,
          dynamicList: dynamicListRes,
          statistics: statisticsRes,
          notifications: notificationsRes
        };
      } catch (error) {
        console.error('加载工作台数据失败:', error);
        
        // 设置错误状态
        this.setPageStatus('isLoading', false);
        this.setPageStatus('isError', true);
        this.setPageStatus('errorMessage', error.message || '数据加载失败，请稍后重试');
        
        // 重新抛出错误，让调用者可以处理
        throw error;
      }
    }),
    
    // 静默加载工作数据 - 不显示loading状态
    loadWorkDataSilent: action(async function() {
      try {
        const result = await cloudHelper.callCloudData(API_ROUTES.WORK_DATA, {});
        
        if (result) {
          // 更新工作数据
          this.updateWorkData(result);
        }
        
        return result;
      } catch (error) {
        console.error('静默加载工作数据失败:', error);
        throw error;
      }
    }),
    
    // 静默加载动态列表 - 不显示loading状态
    loadDynamicListSilent: action(async function() {
      try {
        const result = await cloudHelper.callCloudData(API_ROUTES.DYNAMIC_LIST, {});
        
        if (result && result.list) {
          // 处理时间格式
          const formattedList = result.list.map(item => ({
            ...item,
            time: item.time ? timeHelper.timestamp2Time(item.time, 'M-D h:m') : '',
            timeDesc: pageHelper.fromNow(item.time)
          }));
          
          // 更新动态列表
          this.updateDynamicList(formattedList);
        }
        
        return result;
      } catch (error) {
        console.error('静默加载动态列表失败:', error);
        throw error;
      }
    }),
    
    // 静默加载统计数据 - 不显示loading状态
    loadStatisticsSilent: action(async function() {
      try {
        const result = await cloudHelper.callCloudData(API_ROUTES.STATISTICS, {});
        
        if (result) {
          // 更新统计数据
          this.updateStatistics(result);
        }
        
        return result;
      } catch (error) {
        console.error('静默加载统计数据失败:', error);
        throw error;
      }
    }),
    
    // 静默加载通知信息 - 不显示loading状态
    loadNotificationsSilent: action(async function() {
      try {
        const result = await cloudHelper.callCloudData(API_ROUTES.NOTIFICATIONS, {});
        
        if (result && result.list) {
          // 处理时间格式
          const formattedList = result.list.map(item => ({
            ...item,
            time: item.time ? timeHelper.timestamp2Time(item.time, 'M-D h:m') : '',
            timeDesc: pageHelper.fromNow(item.time)
          }));
          
          // 更新通知列表
          this.updateNotifications(formattedList);
        }
        
        return result;
      } catch (error) {
        console.error('静默加载通知失败:', error);
        throw error;
      }
    }),
    
    // 标记通知为已读
    markNotificationRead: action(async function(id) {
      try {
        const result = await cloudHelper.callCloudData(API_ROUTES.MARK_READ, {
          id: id
        });
        
        if (result) {
          // 从通知列表中移除已读通知
          this.notifications = this.notifications.filter(item => item._id !== id);
        }
        
        return result;
      } catch (error) {
        console.error('标记通知已读失败:', error);
        throw error;
      }
    }),
    
    // 更新页面状态
    setPageStatus: action(function(key, value) {
      if (this.pageStatus.hasOwnProperty(key)) {
        this.pageStatus[key] = value;
      } else {
        console.warn('尝试设置不存在的pageStatus属性:', key);
      }
    }),

    // 初始化
    init: action(function() {
      // 合并开发工具菜单（如果有）
      if (devToolsMenus && devToolsMenus.length > 0) {
        this.quickLinks = [...this.quickLinks, ...devToolsMenus];
      }
      
      // 其他初始化逻辑
    })
  });
}

// 仅在开发环境中添加开发工具菜单
const devToolsMenus = [];

// 导出 indexStore 实例
export const indexStore = createStore();

// 立即初始化
indexStore.init(); 